from app import app, db
from app.models import Customer, Vehicle, Order, Part, OrderItem, User
import random
from datetime import datetime, timedelta
from flask import request, jsonify

@app.cli.command('init-db')
def init_db():
    """清除现有数据并创建新表"""
    db.drop_all()
    db.create_all()
    print('数据库初始化完成。')

def create_test_data():
    """创建测试数据"""
    try:
        # 创建管理员账号
        admin = User(
            username='admin',
            name='系统管理员',
            mobile='13800138001',
            role='admin',
            active=True
        )
        admin.set_password('admin123')
        db.session.add(admin)
        db.session.commit()

        admin = User(
            username='test',
            mobile='13800138001',
            name='庞宝强',
            role='staff',
            active=True
        )
        admin.set_password('test')
        db.session.add(admin)
        db.session.commit()
        
        # 创建客户数据
        customers = [
            Customer(name='张三', phone='13800138001'),
            Customer(name='李四', phone='13800138002'),
            Customer(name='王五', phone='13800138003'),
            Customer(name='赵六', phone='13800138004'),
            Customer(name='孙七', phone='13800138005')
        ]
        db.session.add_all(customers)
        db.session.commit()

        # 创建车辆数据
        vehicles = [
            Vehicle(model='大众帕萨特', plate_number='京A12345', notes='黑色', customer_id=1),
            Vehicle(model='丰田凯美瑞', plate_number='京B12345', notes='白色', customer_id=1),
            Vehicle(model='本田雅阁', plate_number='京C12345', notes='银色', customer_id=2),
            Vehicle(model='别克君威', plate_number='京D12345', notes='红色', customer_id=3),
            Vehicle(model='奥迪A6', plate_number='京E12345', notes='蓝色', customer_id=4)
        ]
        db.session.add_all(vehicles)
        db.session.commit()

        # 创建配件数据
        parts = [
            Part(part_number='P001', name='机油滤芯', unit='个', cost_price=30.0, price=50.0),
            Part(part_number='P002', name='空气滤芯', unit='个', cost_price=50.0, price=80.0),
            Part(part_number='P003', name='刹车片', unit='套', cost_price=200.0, price=300.0),
            Part(part_number='P004', name='火花塞', unit='个', cost_price=25.0, price=40.0),
            Part(part_number='P005', name='机油', unit='升', cost_price=70.0, price=100.0)
        ]
        db.session.add_all(parts)
        db.session.commit()

        # 创建订单数据
        for i in range(10):
            customer = random.choice(customers)
            vehicle = random.choice([v for v in vehicles if v.customer_id == customer.id])
            status_choices = ['待维修', '维修中', '已完成', '已取消']
            order = Order(
                order_number=f'ORD{datetime.now().strftime("%Y%m%d")}{i+1:03d}',
                customer_id=customer.id,
                vehicle_id=vehicle.id,
                created_at=datetime.now() - timedelta(days=random.randint(0, 30)),
                total_amount=0,
                operator='系统管理员',
                status=random.choice(status_choices),
                repair_notes='测试维修备注'
            )
            db.session.add(order)
            db.session.commit()

            # 为每个订单添加2-4个配件项目
            total_amount = 0
            for _ in range(random.randint(2, 4)):
                part = random.choice(parts)
                quantity = random.randint(1, 3)
                amount = quantity * part.price
                total_amount += amount
                
                order_item = OrderItem(
                    order_id=order.id,
                    part_id=part.id,
                    quantity=quantity,
                    price=part.price,
                    amount=amount
                )
                db.session.add(order_item)
            
            # 更新订单总金额
            order.total_amount = total_amount
            db.session.commit()

        print('测试数据创建成功！')
        print(f'创建了 {len(customers)} 个客户')
        print(f'创建了 {len(vehicles)} 辆车辆')
        print(f'创建了 {len(parts)} 个配件')
        print(f'创建了 10 个订单')

    except Exception as e:
        db.session.rollback()
        print('创建测试数据失败：', str(e))

@app.route('/user/edit', methods=['POST'])
def edit_user():
    try:
        data = request.get_json()
        user_id = data.get('id')
        username = data.get('username')
        mobile = data.get('mobile')
        name = data.get('name')
        role = data.get('role')
        active = data.get('active')
        password = data.get('password')

        user = User.query.get(user_id)
        if not user:
            return jsonify({'code': 1, 'message': '用户不存在'})

        user.username = username
        user.mobile = mobile
        user.name = name
        user.role = role
        user.active = active
        
        if password:  # 如果提供了新密码才更新
            user.set_password(password)

        db.session.commit()
        return jsonify({'code': 0, 'message': '更新成功'})
    except Exception as e:
        db.session.rollback()  # 发生错误时回滚事务
        return jsonify({'code': 1, 'message': f'更新失败：{str(e)}'})

@app.route('/user/info/<int:user_id>', methods=['GET'])
def get_user_info(user_id):
    try:
        user = User.query.get(user_id)
        if not user:
            return jsonify({'code': 1, 'message': '用户不存在'})
        return jsonify({'code': 0, 'data': user.to_dict()})
    except Exception as e:
        return jsonify({'code': 1, 'message': f'获取用户信息失败：{str(e)}'})

# 添加用户列表接口
@app.route('/users', methods=['GET'])
def get_users():
    try:
        users = User.query.all()
        return jsonify({
            'code': 0,
            'data': [user.to_dict() for user in users]
        })
    except Exception as e:
        return jsonify({'code': 1, 'message': f'获取用户列表失败：{str(e)}'})

# 修改编辑用户接口的路径，使其更符合 RESTful 规范
@app.route('/users/<int:user_id>', methods=['PUT'])
def update_user(user_id):
    try:
        data = request.get_json()
        user = User.query.get(user_id)
        if not user:
            return jsonify({'code': 1, 'message': '用户不存在'})

        user.username = data.get('username', user.username)
        user.mobile = data.get('mobile', user.mobile)
        user.name = data.get('name', user.name)
        user.role = data.get('role', user.role)
        user.active = data.get('active', user.active)
        
        if data.get('password'):
            user.set_password(data['password'])

        db.session.commit()
        return jsonify({'code': 0, 'message': '更新成功', 'data': user.to_dict()})
    except Exception as e:
        db.session.rollback()
        return jsonify({'code': 1, 'message': f'更新失败：{str(e)}'})

# 获取单个用户信息
@app.route('/users/<int:user_id>', methods=['GET'])
def get_user(user_id):
    try:
        user = User.query.get(user_id)
        if not user:
            return jsonify({'code': 1, 'message': '用户不存在'})
        return jsonify({'code': 0, 'data': user.to_dict()})
    except Exception as e:
        return jsonify({'code': 1, 'message': f'获取用户信息失败：{str(e)}'})

if __name__ == '__main__':
    # with app.app_context():
    #     db.drop_all()  # 删除所有表
    #     db.create_all()  # 创建新表
    #     create_test_data()  # 创建测试数据
    app.run(debug=True) 